package fmfi.chatbox;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.facebook.*;
import com.facebook.model.*;

import fmfi.chatbox.R;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity
{
	private static final int SEND_ACTIVITY_RESULT = 1;
	
	private int messageTextID, authorID, whenID, messageItemID = 1;
	//private boolean messageItemExist = false;
	GraphUser fbUser = null;
	String accessToken = null;
	Messenger messenger = null;
	Date lastRefresh = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_layout);
		
		Session.openActiveSession(this, true, new Session.StatusCallback()
		{
			@Override
			public void call(Session session, SessionState state, Exception exception)
			{
				accessToken = session.getAccessToken();
				Request.executeMeRequestAsync(session, new Request.GraphUserCallback()
				{
					@Override
					public void onCompleted(GraphUser user, Response response)
					{
						if (user != null)
						{
							TextView textUsername = (TextView) findViewById(R.id.textUsername);
							String loggedAs = (String)textUsername.getText();
							//TextView textUserID = (TextView) findViewById(R.id.textUserID);
							textUsername.setText(loggedAs+" "+user.getName());
							//textUserID.setText(user.getId());
							fbUser = user;
							messenger = new Messenger(MainActivity.this, "f862f2945f8e7f9dbf85dc04f76f5e5399fa4f5f", fbUser.getId(), accessToken);
						}
					}
				});
			}
		});
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == SEND_ACTIVITY_RESULT)
		{
			if (resultCode == RESULT_OK)
			{
				buttonRefresh(null);
				Toast.makeText(this, "refreshed", Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.main_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
		case R.id.menu_exit:
			System.exit(0);
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	public void buttonRefresh(View sender)
	{
		boolean insertOnTop = (lastRefresh != null);
		Date now = new Date();
		Message[] messages = messenger.getMessages(lastRefresh);
		lastRefresh = now;
		if (messages != null)
		{
			for (Message msg : messages)
				addPost(msg.message, msg.fbUserName != "" ? msg.fbUserName : msg.fbUserID, msg.datetime, insertOnTop);
		}
		
		/*List<Message> ms = new ArrayList<Message>();
		ms.add(new Message("4", "", "hello", new Date(), 0, 0));
		ms.add(new Message("5", "", "hello", new Date(), 0, 0));
		ms.add(new Message("6", "", "hello", new Date(), 0, 0));
		String res = messenger.fillUsername(ms);
		addPost(ms.get(0).fbUserName, ms.get(0).fbUserID, new Date());
		addPost(ms.get(1).fbUserName, ms.get(1).fbUserID, new Date());
		addPost(ms.get(2).fbUserName, ms.get(2).fbUserID, new Date());
		Toast.makeText(this, res, Toast.LENGTH_LONG).show();*/
	}
	
	public void buttonNewMessage(View sender)
	{
		Intent intent = new Intent(this, SendActivity.class);
		intent.putExtra("fbUserID", messenger.fbUserID);
		intent.putExtra("fbToken", messenger.fbToken);
		intent.putExtra("key", messenger.key);
		startActivityForResult(intent, SEND_ACTIVITY_RESULT);
	}
	
	public void addPost(String content, String author, Date when, boolean insertOnTop)
	{	
		LinearLayout messageList = (LinearLayout)findViewById(R.id.messageList);
		
		// layout v ktorom je cely obsah spravy vratane usera a datumu
		RelativeLayout messageItemLayout = new RelativeLayout(this);
		propertiesOfRelativeLayout(messageItemLayout);
		
		LinearLayout.LayoutParams messageItemLparams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		messageItemLparams.setMargins(10,0,10,15);
		messageItemLayout.setLayoutParams(messageItemLparams);
		
		//Content
		TextView contentView = createContent(content);
		RelativeLayout.LayoutParams textLparams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		textLparams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
		messageItemLayout.addView(contentView, textLparams);
		
		//Author
		TextView authorView = createAuthorOfPost(author);
		RelativeLayout.LayoutParams authorLparams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		authorLparams.addRule(RelativeLayout.BELOW, contentView.getId());
		messageItemLayout.addView(authorView, authorLparams);
		
		//Date
		TextView whenView = createTimeStampOfPost(when);
		RelativeLayout.LayoutParams whenLparams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		whenLparams.addRule(RelativeLayout.BELOW, contentView.getId());
		whenLparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, contentView.getId());
		messageItemLayout.addView(whenView, whenLparams);
		
		//Cely Post vlozi do layoutu
		if (insertOnTop == true)
			messageList.addView(messageItemLayout, 0, messageItemLparams);
		else
			messageList.addView(messageItemLayout, messageItemLparams);
	}
	
	@SuppressWarnings("deprecation")
	private void propertiesOfRelativeLayout(RelativeLayout layout)
	{
		layout.setId(createID("messageItem", messageItemID));
		messageItemID += 1;
		
		if (android.os.Build.VERSION.SDK_INT >= 16) 
			setLayoutBackground(layout);
        else
            layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.post_shape));	
	}
	
	@TargetApi(16)
	private void setLayoutBackground(RelativeLayout layout)
	{
		layout.setBackground(getResources().getDrawable(R.drawable.post_shape));
	}
	
	//ContentView
	private TextView createContent(String cnt)
	{
		TextView textview = new TextView(getApplicationContext());
		textview.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		textview.setPadding(10,5,0,0);
		textview.setText(cnt);
		textview.setTextColor(getResources().getColor(R.color.white));
		textview.setTextAppearance(getApplicationContext(), android.R.style.TextAppearance_Large);
		textview.setGravity(3);
		textview.setId(createID("messageText", messageTextID));
		
		messageTextID += 1;
		return textview;
	}
	
	//AuthorView
	private TextView createAuthorOfPost(String author)
	{
		TextView textview = new TextView(getApplicationContext());
		textview.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		textview.setPadding(15, 8, 0, 0);
		textview.setText(author);
		textview.setTextColor(getResources().getColor(R.color.white));
		textview.setId(createID("author", authorID));
		
		authorID += 1;
		return textview;
	}
	
	//DateView
	private TextView createTimeStampOfPost(Date when)
	{
		TextView textview = new TextView(getApplicationContext());
		textview.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		textview.setPadding(0, 8, 15, 0);
		String date = formatDate(when);
		textview.setText(date);
		textview.setTextColor(getResources().getColor(R.color.white));
		textview.setId(createID("when", whenID));
		
		whenID += 1;
		return textview;
	}
	
	private int createID(String name, int number)
	{
		int viewID = 0;
		int nameSum = 0;
		
		for (int i = 0; i < name.length(); i++) 
			nameSum += Character.getNumericValue(name.charAt(i));
		viewID = nameSum + number;
		
		return viewID;
	}
	
	
	@SuppressLint("SimpleDateFormat")
	private String formatDate(Date when)
	{
		String result = new SimpleDateFormat("dd.MM.yyyy' 'HH:mm").format(when);
		return result;
	}
}
